package file.homework;
import java.io.*;
import java.util.Scanner;

/**
 * 找到包含关键字的文件,并删除
 */
public class Contains {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        String rootPath = scanner.nextLine();
        String word = scanner.nextLine();

        File rootDir = new File(rootPath);
        if (!rootDir.isDirectory()) {
            System.out.println("WRONG!");
        }
        //查找
        scanDir(rootDir,word);
    }
    public static void scanDir(File rootDir,String words){
        Scanner scanner = new Scanner(System.in);
        // 列出file中有哪些类
        File[] files = rootDir.listFiles();
        if (files == null) {
            return;
        }
        // 遍历当前内容
        // 普通文件 -- 监测是否是要删除的文件
        // 文件夹 -- 递归找
        for (File f : files) {
            if (f.isFile()) {
                if (containsWords(f,words)){
                    System.out.println(f.getAbsolutePath() + "确定要删除吗?y/n");
                    String choice = scanner.next();
                    if (choice.equals("y") || choice.equals("Y")){
                        f.delete();
                    }
                }
            }else if (f.isDirectory()) {
                scanDir(f,words);
            }
        }
    }
    public static boolean containsWords(File file,String words){
        // f中的内容读出来
        StringBuilder stringBuilder = new StringBuilder();
        try(Reader reader = new FileReader(file)) {
            char[] buffer = new char[1024];
            while (true) {
                int len = reader.read(buffer);
                if (len == -1) {
                    break;
                }
                // 放到 StringBuilder中
                stringBuilder.append(buffer,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        // indexOf 返回的是下标,没有的话返回-1
        return stringBuilder.indexOf(words) != -1;
    }
}
